<template>
  <div style="position: relative; display: inline-block">
    <el-popover
      :visible="showFields"
      placement="bottom-start"
      trigger="click"
      :width="250"
      popper-style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
    >
      <template #reference>
        <el-button :icon="Check" @click="showFields = !showFields"
          >选择查询字段</el-button
        >
      </template>
      <div
        style="
          background: white;
          border: 1px solid #ddd;
          padding: 8px;
          border-radius: 4px;
          white-space: nowrap;
        "
      >
        <GapedColumn>
          <div
            style="
              display: flex;
              justify-content: flex-end;
              margin-top: 8px;
              gap: 8px;
            "
          >
            <el-tooltip content="清除所有选择" placement="top">
              <el-button
                circle
                :icon="CircleCloseFilled"
                class="action-button danger"
                @click="clearAll"
              />
            </el-tooltip>
            <el-tooltip content="选择所有字段" placement="top">
              <el-button
                :icon="CircleCheckFilled"
                circle
                class="action-button primary"
                @click="selectAll"
              />
            </el-tooltip>

            <div
              style="
                margin-left: 8px;
                border-left: 1px solid #e0e0e0;
                padding-left: 8px;
              "
            >
              <el-tooltip content="取消并关闭" placement="top">
                <el-button
                  :icon="Close"
                  circle
                  class="control-button"
                  @click="handleCancel"
                />
              </el-tooltip>
              <el-tooltip content="应用选择" placement="top">
                <el-button
                  :icon="Check"
                  circle
                  class="control-button success"
                  @click="handleApply"
                />
              </el-tooltip>
            </div>
          </div>
          <div
            v-for="field in sortedFields"
            :key="field.name"
            style="display: flex; align-items: center; margin-bottom: 6px"
          >
            <el-checkbox v-model="selectedFields" :label="field.name" />
            <span style="margin-left: 6px">{{
              `${field.label}(${field.field_type})`
            }}</span>
          </div>
        </GapedColumn>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {
  CircleCheckFilled,
  Close,
  Check,
  CircleCloseFilled,
} from '@element-plus/icons-vue'
import { ref, watch, computed, onMounted } from 'vue'
import type { OptionField } from '@/models/warning'
import GapedColumn from '@/core/components/GapedColumn.vue'

const props = defineProps<{
  modelValue: string[]
  optionFields: Array<OptionField>
  tableName: string
  applyStorage?: boolean
}>()

const STORAGE_KEY = 'selectedSearchFields'

const saveSelected = (fields: string[]) => {
  if (props.applyStorage) {
    localStorage.setItem(
      `${STORAGE_KEY}_${props.tableName}`,
      JSON.stringify(fields)
    )
  }
}

const loadSelected = (): string[] => {
  if (props.applyStorage) {
    const saved = localStorage.getItem(`${STORAGE_KEY}_${props.tableName}`)
    if (saved) {
      return JSON.parse(saved)
    }
  }
  return props.optionFields.map(field => field.name)
}

const initSelectedFields = () => {
  if (!props.modelValue || props.modelValue.length === 0) {
    const loadedFields = loadSelected()
    if (loadedFields.length > 0) {
      selectedFields.value = loadedFields
      emit('update:modelValue', loadedFields)
    }
  }
}

onMounted(() => {
  initSelectedFields()
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
}>()

const showFields = ref(false)
const selectedFields = ref([...props.modelValue])

const sortedFields = computed(() => {
  return [...props.optionFields].sort((a, b) => {
    const aIndex = selectedFields.value.indexOf(a.name)
    const bIndex = selectedFields.value.indexOf(b.name)

    if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex
    if (aIndex !== -1) return -1
    if (bIndex !== -1) return 1
    return a.name.localeCompare(b.name) // 添加按字段名称排序
  })
})

watch(
  () => props.optionFields,
  () => {
    initSelectedFields()
  },
  { immediate: true }
)

const selectAll = () => {
  selectedFields.value = props.optionFields.map(field => field.name)
}

const clearAll = () => {
  selectedFields.value = []
}

const handleCancel = () => {
  showFields.value = false
  selectedFields.value = [...props.modelValue]
}

const handleApply = () => {
  showFields.value = false
  saveSelected(selectedFields.value)
  emit('update:modelValue', selectedFields.value)
}
</script>

<style scoped>
.action-button {
  border: none;
  background-color: transparent;
  color: var(--el-color-primary);
}

.action-button.danger {
  color: var(--el-color-danger);
}

.action-button.primary {
  color: var(--el-color-primary);
}

.control-button {
  border: 1px solid var(--el-border-color);
  background-color: white;
}

.control-button.success {
  color: var(--el-color-success);
  border-color: var(--el-color-success-light-5);
}
</style>
